//
//  BLTouchBackground.m
//  BLTouchBackground.m
//
//  Created by 郑林琴 on 15/2/7.
//  Copyright (c) 2015年 Binglin All rights reserved.
//

#import "BLTouchBackground.h"

@implementation BLTouchBackground

+ (instancetype)touchBackground{
    BLTouchBackground *_background = [[BLTouchBackground alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _background.backgroundColor = [UIColor lightGrayColor];
    _background.touchDismiss = YES;
    return _background;
}

- (void)awakeFromNib{
    [super awakeFromNib];
    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4f];
    self.touchDismiss = YES;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    if (CGRectContainsPoint(self.touchDismissRect, [touch locationInView:self])) {
        if (self.touchDismiss) {
            [self dismiss];
        }
    }
}


#pragma mark - dismiss
- (void)dismiss{
    [self dismissWithAnimate:YES];
}

- (CGRect)touchDismissRect{
    return self.bounds;
}

- (void)dismissWithAnimate:(BOOL)animate{
    
    [UIView animateWithDuration:0.3f animations:^{
        CGRect frame = self.animateView.frame;
        frame.origin.y = self.frame.size.height;
        self.animateView.frame = frame;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        if (self.completion) {
            self.completion();
        }
    }];
}


#pragma mark - show
- (void)showFromView:(UIView *)view{
    [self showFromPoint:CGPointZero animate:YES];
}

- (void)showFromPoint:(CGPoint)point{
    [self showFromPoint:CGPointZero animate:YES];
}


- (void)showFromPoint:(CGPoint)point animate:(BOOL)animate{
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    self.frame = [UIApplication sharedApplication].keyWindow.bounds;
    
    CGRect frame = self.animateView.frame;
    frame.origin.y = self.frame.size.height;
    self.animateView.frame = frame;
    
    [UIView animateWithDuration:.15f animations:^{
        
        CGRect frame = self.animateView.frame;
        frame.origin.y = self.frame.size.height - frame.size.height;
        self.animateView.frame = frame;
    }];
}


- (UIView *)animateView{
    return self.bottomContainer;
}

@end
